package com.whz.gateway.limit.sentinel;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.whz.gateway.common.GatewayMessageAccessor;
import com.whz.gateway.common.web.GatewayResponseBody;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

/**
 * @author whz
 */
@Configuration
@ConditionalOnProperty(name = "spring.cloud.sentinel.enabled", havingValue = "true")
public class GatewaySentinelConfigure {

    @Bean
    @ConditionalOnMissingBean
    public BlockRequestHandler defaultBlockRequestHandler() {
        return (exchange, t) ->
                GatewayResponseBody.builder()
                                   .code(HttpStatus.TOO_MANY_REQUESTS.value())
                                   .message(HttpStatus.TOO_MANY_REQUESTS.name())
                                   .path(exchange.getRequest().getPath().toString())
                                   .method(exchange.getRequest().getMethodValue())
                                   .timestamp(System.currentTimeMillis())
                                   .error(GatewayMessageAccessor.getMessage("gateway.sentinel.TOO_MANY_REQUEST"))
                                   .build()
                                   .sendToResponse();
    }
}